package ua.kiev.tosik.price.database.connectors;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;


abstract public class ConnectorFactory implements IConnector {

	protected Connection connection;
	protected String errorMessage;
	protected static Logger logger = Logger.getLogger("ua.kiev.tosik.price.database.connectors");
	protected NumberFormat numberFormat = new DecimalFormat("#,###");

	public static ConnectorFactory getInstance(String dbType) throws IllegalDbType {
		if ( "Derby".equalsIgnoreCase(dbType) ) {
			return ConnectorDerby.getInstance();
		} else if ( "PostgreSql".equalsIgnoreCase(dbType) || "Postgres".equalsIgnoreCase(dbType) ) {
			return ConnectorPgsql.getInstance();
		} else {
			throw new IllegalDbType("Database [" + dbType + "] is not supported!");
		}
	}

	@Override
	public Connection getConn() throws SQLException {
		return connection;
	}

	@Override
	public void close() throws SQLException {
		connection.close();
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public static class IllegalDbType extends Exception {

		private String message;

		public IllegalDbType(String msg) {
			super(msg);
			message = msg;
		}

		public String getMessage() {
			return message;
		}

		public String getLocalizedMessage() {
			return getMessage();
		}
	}

	protected String getStructure(String fileName) throws Exception {
		logger.info("Get Sql script [" + fileName + "]");
		String sql = "";
		File sqlScript = new File(fileName);
		if (sqlScript.exists()) {
			try {
				sql = FileUtils.readFileToString(sqlScript, "utf-8");
				logger.debug("Sql script [" + fileName + "] loaded!");
				if (sql.length() == 0) {
					logger.error("Sql script is empty!");
					throw new Exception(fileName + " is empty!");
				}
			} catch (Exception e) {
				logger.error(e.getLocalizedMessage());
				e.printStackTrace();
			}
		} else {
			logger.fatal("Can't load " + fileName + "! File not found!");
			throw new Exception(fileName + " not found!");
		}
		return sql;
	}
	

}
